package com.example.simplesvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SocketChannel;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;


@Service
public class MySpringServiceWithTimer implements DisposableBean {


    private static Logger log = LoggerFactory.getLogger(MySpringServiceWithTimer.class);

    private volatile boolean serverStopping = false;

    private Timer timer = new Timer();


    public void runTask() {


        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 模拟一个后台检查任务
                while (true) {
                    if (serverStopping) {
                        //服务器正在退出
                        log.info("服务器关闭中，退出执行");
                        return;
                    }

                    log.info("后台进程检查程序，模拟流式消费MQ消息");


                    //1 sleep，wait，join等操作 可能会引起因为中断引起 InterruptedException
                    try {
                        Thread.sleep(5000);
                    }catch (InterruptedException e) {
                        log.info("线程被中断，退出执行");
                        return;
                    }

                    //2 InterruptibleChannel 网络通信操作，可能会引起因为中断引起 ClosedByInterruptException
                    try {
                        InetSocketAddress addr = new InetSocketAddress("www.163.com",80);
                        //建立连接时可如果线程被中断，就会抛出ClosedByInterruptException
                        SocketChannel ch = SocketChannel.open(addr);
                        ByteBuffer bb = ByteBuffer.allocate(4096);
                        //读取数据时可如果线程被中断，就会抛出ClosedByInterruptException
                        ch.read(bb);
                        bb.flip();
                        log.info("received data " + new String( bb.array()));
                    }catch (ClosedByInterruptException e) {
                        log.info("线程被中断，退出执行");
                        return;
                    }catch (Exception e) {
                        log.error("通信失败", e);
                    }

                    //3 检查线程状态，若处于中断状态，退出执行
                    if(Thread.currentThread().isInterrupted()) {
                        log.info("线程被中断，退出执行");
                        return;
                    }

                }
            }
        }, TimeUnit.SECONDS.toMillis(10));
    }

    @Override
    public void destroy() {

        this.serverStopping = true;

        try {
            shutdownTimer();
        } catch (Exception e) {
            log.error("关闭timer失败", e);
        }
    }

    private void shutdownTimer() {
        timer.cancel();
    }

}
